from datetime import datetime
import json

from .models.kline import Kline
from .models.order import Orders
from .models.goods import Goods
import time

from django_redis import get_redis_connection

redis_kline_key = 'kline-start'
redis_kline_60min_key = 'kline-60min-start'
redis_kline_1day = 'kline-1day-start'


# 处理K线数据
def tick():
    goodsList = Goods.objects.values()
    conn = get_redis_connection()
    val = conn.get(redis_kline_key)
    redisTime = 0
    if val == None:
        one = Orders.objects.order_by("created").first()
        redisTime = one.created
    else:
        redisTime = json.loads(val)

    # 时间大于当前
    if redisTime > int(time.time()) + 30:
        return
    lastTime = int(redisTime) + 60
    timeRange = [int(redisTime), lastTime]
    for item in goodsList:
        order_list = Orders.objects.filter(goods_sn=item['sn'], created__range=timeRange).order_by("created").values()
        # list1 = list(order_list)
        if len(order_list) > 0:
            saveKline(order_list, item['sn'], '1min')

    conn.set(redis_kline_key, lastTime)
    print('kline Tick! time is: %s timer %s' % (datetime.now(),redisTime))

def tick60min():
    goodsList = Goods.objects.values()
    conn = get_redis_connection()
    val = conn.get(redis_kline_60min_key)
    redisTime = 0
    if val == None:
        one = Orders.objects.order_by("created").first()
        redisTime = one.created
    else:
        redisTime = json.loads(val)

    # 时间大于当前
    if redisTime > int(time.time()) + 60 * 30:
        return
    lastTime = int(redisTime) + 60 * 60
    timeRange = [int(redisTime), lastTime]
    for item in goodsList:
        order_list = Orders.objects.filter(goods_sn=item['sn'], created__range=timeRange).order_by("created").values()
        # list1 = list(order_list)
        if len(order_list) > 0:
            saveKline(order_list,item['sn'],'60min')

    conn.set(redis_kline_60min_key, lastTime)
    print('kline 60min Tick! time is: %s timer %s' % (datetime.now(), redisTime))

def tick1day():
    goodsList = Goods.objects.values()
    conn = get_redis_connection()
    val = conn.get(redis_kline_1day)
    redisTime = 0
    if val == None:
        one = Orders.objects.order_by("created").first()
        redisTime = one.created
    else:
        redisTime = json.loads(val)

    # 时间大于当前
    if redisTime > int(time.time()) + 60 * 60 * 12:
        return

    lastTime = int(redisTime) + 60 * 60 * 24
    timeRange = [int(redisTime), lastTime]
    for item in goodsList:
        order_list = Orders.objects.filter(goods_sn=item['sn'], created__range=timeRange).order_by("created").values()
        # list1 = list(order_list)
        if len(order_list) > 0:
            saveKline(order_list,item['sn'],'1day')

    conn.set(redis_kline_1day, lastTime)
    print('kline 1day Tick! time is: %s timer %s' % (datetime.now(), redisTime))

def saveKline(order_list,sn,period):
    kline = Kline()
    firstO = order_list.first()  # 开盘
    kline.open = firstO['price']
    lastO = order_list.last()  # 收盘
    kline.close = lastO['price']
    maxRange = getMaxRange(order_list)

    kline.low = maxRange['low']  # 最低
    kline.high = maxRange['high']  # 最高
    kline.vol = ''
    kline.count = len(order_list)
    kline.amount = getAmount(order_list)  # 成交量
    kline.period = period
    kline.created = int(time.time())
    kline.goods_sn = sn  # 商品编号
    kline.save()

# 获取成交量
def getAmount(r):
    amount = 0
    for item in r:
        amount = amount + item['amount']
    return amount

def getMaxRange(r):
    low = 0
    high = 0
    for item in r:
        if low == 0:
            low = item['price']
            high = item['price']
            continue
        if low > item['price']:
            low = item['price']
        if high < item['price']:
            high = item['price']
    return {'low':low,'high':high}